import { sendMSMCAPI } from "@/apis/user"
import type { codeType } from "@/types/user"
import { showToast, type FormInstance } from "vant"
import { ref, type Ref } from "vue"

export function userMobileCode(mobile: Ref<string>, type: codeType = 'login') {
    // 短信验证吗登录
// 点击发送验证码的时候要校验手机号是否输入
const formRef = ref<FormInstance>()
const time = ref(0)
let timeId: number
const onSend = async () => {
    // 判断是否已经发送了验证码
    if(time.value > 0) return
    // 判断是否输入了手机号
    await formRef.value?.validate('mobile')
    // 发送验证码
    const res = await sendMSMCAPI(mobile.value, type)
    console.log(res.data.code)
    // 显示验证码
    showToast({
        message:res.data.code,
        duration: 3000
    })
    // 处理倒计时
    time.value = 60
    if(timeId) clearInterval(timeId)
    // 开启定时器函数
    timeId = setInterval(() => {
        time.value--
        // 如果倒计时等于0就清楚定时器
        if(time.value <= 0){
            clearInterval(timeId)
        }
    },1000)
}
    return {
        onSend,
        time,
        formRef
    }
}